/*
 * IdentificatorReceiver.cpp
 *
 *  Created on: 27/06/2014
 *      Author: Caina
 */

#include "IdentificatorReceiver.h"

IdentificatorReceiver::IdentificatorReceiver() :
		socket(UDPSocket(7778)) {

}

IdentificatorReceiver::~IdentificatorReceiver() {

}

void IdentificatorReceiver::run() {
	unsigned int peerId;
	char messageType;

	while (Globals::active.get()) {
		UDPPacket incoming_packet;
		if (socket.recv(1024, incoming_packet)) {
			auto queue = ByteQueue(incoming_packet.bytes);

			messageType = queue.pop<char>();
			peerId = queue.pop<unsigned int>();

			if (messageType == MessageTypes::IDENTIFIER) {
				Globals::peer.lock();
				if (peerId == Globals::peer.get().get_identifier()) {
					Globals::peer.get().set_ip_address(incoming_packet.host_ip);
					Globals::identified.lock();
					Globals::identified.get() = true;
					Globals::identified.unlock();
					Globals::peers.lock();
						Globals::peers.get()[incoming_packet.host_ip] =
								SDL_GetTicks();
						Globals::peers.unlock();
				} else {
					printf("Par %x chegou:\n",incoming_packet.host_ip);
					Globals::peers.lock();
					if (Globals::peer.get().get_ip_address()
							== Balancer::get_manager_ip()
							&& (Globals::peers.get().count(
									incoming_packet.host_ip) == 0)) {

						Globals::peers.unlock();
						Thread balancer([] () {
							auto& balancer = Balancer::get_instance();
							balancer.run(Balancer::NEW_NODE);
						});

						Globals::peers.lock();
						Globals::peers.get()[incoming_packet.host_ip] =
								SDL_GetTicks();
						Globals::peers.unlock();

						balancer.start();
					} else {
						Globals::peers.unlock();
					}
				}
				Globals::peer.unlock();
			}
		}
		SDL_Delay(20);
	}
}
